﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Caching;
using System.Web.SessionState;
using yncTech.BusinessObjects;
using yncTech.BusinessComponent;
using yncTech.Common;
/// <summary>
///LoginUserInfo 的摘要说明
/// </summary>
public class LoginUserInfo
{
    private LoginUserInfo()
    {
    }
    private static SystemBC systemBC = new SystemBC();

    public static bool IsAuthenticated
    {
        get
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null || HttpContext.Current.Session["LoginUserSessionId"] == null)
            {
                return false;
            }

            if (HttpContext.Current.Session["LoginUserSessionId"] != null)
            {
                return true;
            }
            return false;

        }
    }

    public static LoginUserEnity CurrentUser
    {

        get
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null)
            {
                throw new BusinessException() { ExceptionType = ExceptionType.TimeOut };
            }

            if (HttpContext.Current.Session["LoginUserSessionId"] != null)
            {
                return HttpRuntime.Cache[HttpContext.Current.Session["LoginUserSessionId"].ToString()] as LoginUserEnity;
            }
            else
            {
                return null;
            }
        }
    }

    public static void LoginOut()
    {
        if (IsAuthenticated)
        {
            HttpContext.Current.Session.Remove("LoginUserSessionId");

        }
    }

    public static void Login(string userName, string password)
    {
        TSUsers user = systemBC.GetUsersByLoginName(userName);
        if (!user.es.HasData)
        {
            throw new BusinessException("用户名不存在!");
        }
        if (user.IsActive.Value != (short)ActiveStatus.Active)
        {
            throw new BusinessException("帐号已锁定!");
        }
        if (!user.Password.ToLower().Equals(password.ToLower()))
        {
            throw new BusinessException("密码不正确!");
        }
        user.LastLoginDate = DateTime.Now;

        WebHelper.SetCookie("yncTech.LoginNo", userName);


        LoginUserEnity userInfo = new LoginUserEnity();
        userInfo.UserID = user.UserID.Value;
        userInfo.LoginName = userName;

        TSUserRolesQuery q1 = new TSUserRolesQuery("Q1");
        TSRoleQuery q2 = new TSRoleQuery("Q2");
        TSFunctionsQuery q3 = new TSFunctionsQuery("Q3");
        TSRoleFunctionsQuery q4 = new TSRoleFunctionsQuery("Q4");

        q3.SelectAll();
        q1.InnerJoin(q2).On(q1.RoleID == q2.RoleID && q2.IsActive == true);
        q1.InnerJoin(q4).On(q1.RoleID == q4.RoleID);
        q1.InnerJoin(q3).On(q4.FunctionID == q3.FunctionID && q3.IsActive == true);
        q1.Where(q1.UserID == user.UserID);

        q1.OrderBy(q3.ParentID.Ascending, q3.Sequence.Ascending);


        TSUserInfo loginUser = new TSUserInfo();
        loginUser.LoadByPrimaryKey(user.UserID.Value);
        userInfo.UserName = loginUser.UserName.Trim();
        userInfo.ThirdUnitID = loginUser.ThirdUnitID.Value;
        //userInfo.Title = loginUser.Title.Trim();
        //userInfo.Deptname = loginUser.DeptName.Trim();
        userInfo.UserEntity = loginUser;



        userInfo.Functions = q1.LoadDataTable();
        userInfo.UserID = user.UserID.Value;

        //load the user role
        TSUserRolesQuery q5 = new TSUserRolesQuery("q5");

        q2.SelectAll();
        q2.InnerJoin(q5).On(q2.RoleID == q5.RoleID);
        q2.Where(q5.UserID == user.UserID);
        userInfo.UserRoles = q2.LoadDataTable();



        user.Save();
        HttpContext.Current.Session["LoginUserSessionId"] = HttpContext.Current.Session.SessionID;
        HttpRuntime.Cache.Insert(HttpContext.Current.Session.SessionID, userInfo, null, DateTime.MaxValue,
            TimeSpan.FromMinutes(yncSettings.SessionTimeOut), CacheItemPriority.NotRemovable, null);
    }

    public class LoginUserEnity
    {
        public LoginUserEnity()
        {
            UserType = "";
        }
        /// <summary>
        /// login user id.
        /// </summary>
        public decimal UserID { get; set; }
        public string UserName { get; set; }
        public string LoginName { get; set; }
        public decimal ThirdUnitID { get; set; }
        public TSUserInfo UserEntity { get; set; }

        public string Title { get; set; }
        public string DeptNo { get; set; }
        public string Deptname { get; set; }
        public string UserType { get; set; }


        public DataTable UserRoles { get; set; }
        public DataTable Functions { get; set; }

        public bool HasFunction(string function)
        {
            return Functions.AsEnumerable().Where(row => row["URL"].ToString() == function).Count() > 0;
        }

        public bool IsAdmin
        {
            get
            {
                if (UserRoles == null)
                {
                    return false;
                }
                return UserRoles.AsEnumerable().Where(row => row["RoleName"].ToString().ToLower() == "admin").Count() > 0;
            }
        }

        public HttpSessionState UserSession { get; set; }
    }

    /// <summary>
    /// 检查用户与密码是否匹配
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="passWord"></param>
    /// <returns></returns>
    public static bool CheckUser(string userName, string passWord)
    {
        TSUsers user = systemBC.GetUsersByLoginName(userName);

        if (!user.es.HasData)
        {
            return false;
        }
        if (user.IsActive.Value != (short)ActiveStatus.Active)
        {
            return false;
        }
        if (!user.Password.ToLower().Equals(passWord.ToLower()))
        {
            return false;
        }

        return true;
    }
}